<?php

namespace app\job;

use app\Constants;
use app\service\alipayWapService;
use app\service\communityZftGateService;
use app\service\propertyService;
use app\service\RedisQueueService;
use app\service\webService;
use app\service\zftService;
use app\zftpay\service\apiService;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;
use think\queue\Job;
use think\queue\ShouldQueue;

class ZftSettleConfirmOrder implements ShouldQueue
{
    public $jobData;

    public function __construct($jobData)
    {
        $this->jobData = $jobData;
    }
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data){
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        print("<info>ZftSettleConfirmrder Job Started. attempts: ".$job->attempts()."--id".$this->jobData["id"]."</info> \n");
        //执行收单交易结算
        if ($job->attempts() > 3) {
            //记录开票推送失败的记录
            $job->delete();

        }
        $isJobDone = $this->doJob($this->jobData);
        print("<info>ZftSettleConfirmrder Result Data is: ".$isJobDone."--id".$this->jobData["id"]."</info> \n");

        if ($isJobDone=="success") {
            $jobQueueName  	  = "app\job\ZftSettleOrder";
            $jobData       	  = [ 'id' => $this->jobData["id"] ] ;
            $res=Queue::push($jobQueueName,$jobData);
            $job->delete();
        }else{
            print("<info>ZftSettleConfirmrder fail. attempts: ".$job->attempts()."--id".$this->jobData["id"]."</info> \n");
            if($isJobDone=="fail"){
                $job->delete();
                (new RedisQueueService())->push("settleConfirmOrderFailed",$data["id"]);
                return ;
            }
            if ($job->attempts() > 3) {
                //记录开票推送失败的记录
                $job->delete();
                (new RedisQueueService())->push("ZftSettleConfirmOrderFailed",$data["id"]);

            }
        }
    }
    public function doJob($data){
        $info=Db::table("zft_order_success")->where("uid",$data["id"])->find();
        if(empty($info)){
            print("<info>ZftSettleConfirmOrder job Data is: 订单不存在</info> \n");
            return (new RedisQueueService())->push("ZftSettleConfirmOrderFailed",$data["id"]." 订单不存在");
            return "fail";
            return false;

        }
        $propertyZftInfo=(new propertyService())->propertyZftByComId($info["community_id"]);
        if(empty($propertyZftInfo)){

            print("<info>ZftSettleConfirmOrder job Data is: 直付通配置为空</info> \n");
            return (new RedisQueueService())->push("ZftSettleConfirmOrderFailed",$data["id"]." 直付通配置为空");
            return "fail";
            return false;
        }
        //$api=new zftService();
        $api=new alipayWapService();
        $amount=round($propertyZftInfo["taxrate"]*$info["order_money"],2);
//        if($amount<=0){
//            Db::table("zft_order_success")->where("id",$info["uid"])->update([
//                "settle_status"=>1
//            ]);
//            print("<info>ZftSettleConfirmOrder job Data is: 金额为零</info> \n");
//            return ;
//        }
        $royalty_parameters=array(
            'royalty_type'=>'transfer',//'',
            'trans_in_type'=>'loginName',//收入方账户类型userId
            'trans_in'=>$propertyZftInfo["binding_alipay_logon_id"],//收入方账户\linan2421@163.com  2088070839250462
            'amount'=>$info["order_money"],//分账金额
        );

        if(isset($propertyZftInfo["trans_in_type"]) && $propertyZftInfo["trans_in_type"]=="userId"){
            $royalty_parameters=array(
                'royalty_type'=>'transfer',//'',
                'trans_in_type'=>'userId',//收入方账户类型userId
                'trans_in'=>$propertyZftInfo["seller_id"],//收入方账户\linan2421@163.com  2088070839250462
                'amount'=>$info["order_money"],//分账金额
            );
        }
        $data= array(
            'out_trade_no'=> $info["out_trade_no"],
            'trade_no'=>$info["trade_no"],
            'royalty_parameters'=>$royalty_parameters,
        );
        $result = $api->settleComfirm(json_encode($data));
        Log::write($result);
        $add["result_code"]=$result->code;
        $add["order_uid"]=$info["uid"];
        $add["create_time"]=date("Y-m-d H:i:s");
        print("<info>HZftSettleConfirmOrder job Data is: ".var_export($result,true)."</info> \n");
        if($result->code=="10000"){
            $add["result_msg"]="成功";
            $add["out_request_no"]=$result->out_request_no;
            $add["trade_no"]=$result->trade_no;
            $add["settle_amount"]=$result->settle_amount;
            $add["source"]="queue";
            $add["community_id"]=$info["community_id"];
            $add["trans_in_type"]=$royalty_parameters["trans_in_type"];
            $add["trans_in"]=$royalty_parameters["trans_in"];
            Db::table("zft_log_settle_confirm")->insert($add);
        }else{
            $add["out_request_no"]=$info["out_trade_no"];
            $add["trade_no"]=$info["trade_no"];
            $add["result_msg"]=$result->sub_msg;
            $add["sub_code"]=$result->sub_code;
            $add["source"]="queue";
            $add["community_id"]=$info["community_id"];
            $add["trans_in_type"]=$royalty_parameters["trans_in_type"];
            $add["trans_in"]=$royalty_parameters["trans_in"];
            if (in_array($result->sub_code, Constants::$settleConfirmErrorCode)) {
                $add["close_pay_status"]="1";
                (new communityZftGateService())->setPayStatus($info["gate_id"],"0");
            }
            Db::table("zft_log_settle_confirm_fail")->insert($add);
            if (in_array($result->sub_code, Constants::$settleConfirmErrorCode)) {
                return "fail";
            }
            return "retry";
            return false;
        }
        print("<info>HZftSettleConfirmOrder job Data is: ".var_export($result,true)."</info> \n");

        return "success";
        return true;
    }

    public  function  handle(){

    }

}